<template>
    <div class="CustomerLossWarning">
      <div class="select-module">
        <el-card>
          <el-row>
            <el-col :span="5">
              <div class="child-module">
                <span class="name">{{$t('select.CustomerType')}}</span>
                <el-select v-model="typeVal"
                           @change="changeType"
                           multiple collapse-tags>
                  <el-option
                    v-for="item in typeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </el-col>
            <el-col :span="5">
              <div class="child-module">
                <span class="name">{{$t('select.CustomerIndusty')}}</span>
                <el-select v-model="industryVal"
                           @change="changeIndustry"
                           multiple collapse-tags>
                  <el-option
                    v-for="item in industryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </el-col>
            <el-col :span="5">
              <div class="child-module child-input">
                <span>{{$t('select.CustomerValue')}}</span><span style="margin:0 10px;">&gt;</span>
                <el-input v-model="scoreVal" placeholder="10"></el-input>
              </div>
            </el-col>
            <el-col :span="9">
              <div class="child-module">
                <span class="name" style="margin-left: 10px;">{{$t('select.TimeFrame')}}</span>
                <el-date-picker
                  v-model="timeRange"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  @change="changeTimeRange"
                  :range-separator="$t('bidding.to')"
                  :start-placeholder="$t('bidding.startTime')"
                  :end-placeholder="$t('bidding.endTime')">
                </el-date-picker>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>
      <div class="box-part">
        <div v-for="value in boxData" class="box">
          <div v-for="(v,k) in value" class="box-cont">
            <span class="mediumFont">{{k}}</span>
            <span class="regularFont">{{comdify(v.toString())}}</span>
          </div>
        </div>
      </div>
      <el-card>
        <span class="title">{{$t('CustomerLossWarning.NewLossRiskUsers')}}</span>
        <div class="nodata" v-if="showNoData.echartMix">No Data</div>
        <div class="echartMix" v-loading="loading.echartMix"></div>
      </el-card>
      <div class="left-lists">
        <el-row :gutter="20">
          <el-col :span="14">
            <el-card style="position:relative;height:75vh;">
              <div class="title">{{$t('CustomerLossWarning.LossRiskUserRanking')}}</div>
              <div class="tabThree">
                <el-radio-group v-model="tabBtn" size="mini" @change="changeTab(tabBtn)">
                  <el-radio-button label="0">{{$t('CustomerLossWarning.CommercialCustomers')}}</el-radio-button>
                  <el-radio-button label="1">{{$t('CustomerLossWarning.ChannelCustomers')}}</el-radio-button>
                </el-radio-group>
              </div>
              <ul class="list-part" v-loading="loading.listPart">
                <li v-for="(list,index) in listData" @click="changeEcharts(list,index)"
                    :key="index"
                    :class="{'activeColor':flag == index}">
                  <span>{{index+ (listNum - 1) * 10 +1}}.</span>
                  <span>{{list.bp_name}}</span>
                  <span style="float:right;">价值：{{list.avg_score}}</span>
                </li>
              </ul>
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalPage">
              </el-pagination>
            </el-card>
          </el-col>
          <el-col :span="10">
            <el-card style="height:35vh;">
              <span class="title">{{$t('CustomerLossWarning.TradingCycle')}}</span>
              <div class="nodata" v-if="showNoData.echart1">No Data</div>
              <div class="echart1" v-loading="loading.echart1"></div>
            </el-card>
            <el-card style="margin-top:2vh;height:38vh;">
              <span class="title">{{$t('CustomerLossWarning.RecentTransactions')}}</span>
              <div class="nodata" v-if="showNoData.echart2">No Data</div>
              <div class="echart2" v-loading="loading.echart2"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import {getUsername} from '../../utils/auth'
    export default {
      name: "CustomerLossWarning",
      data(){
        return {
          testPort: '',
          typeVal: '',
          typeOptions: [],
          industryVal: '',
          industryOptions: [],
          scoreVal: '',
          timeRange: [],
          resBoxData: {},
          boxData: {},
          echartDom:{
            echartMix: '',
            echart1: '',
            echart2: '',
          },
          showNoData:{
            echartMix: false,
            echart1: false,
            echart2: false
          },
        loading:{
          echartMix: false,
          echart1: false,
          echart2: false,
          listPart: false
        },
          flag: 0,
          tabBtn: '0',
          listData: [],
          listNum: 1,
          currentPage: 1,
          totalPage: 1,
          pageSize: 10
        }
      },
      methods:{
        // 千分位
        comdify(n) {
          var re = /\d{1,3}(?=(\d{3})+$)/g;
          var n1 = n.replace(/^(^-?\d+)((\.\d+)?)$/, function (s, s1, s2) {
            return s1.replace(re, "$&,") + s2
          })
          return n1
        },
        // 下拉框
        async getSelectData(){
          let res = await this.axios.post(`${this.testPort}/customerChurnAnalysis/selectDrop`,{
            "username":getUsername()
          })
          let resData = res.data.data
          let typeOptions = resData.bpTypeSelect.map(item => ({value: item, label: item}))
          let industryOptions = resData.industrySelect.map(item => ({value: item, label: item}))
          this.typeOptions = typeOptions
          this.industryOptions = industryOptions
        },
        changeIndustry(){
          this.initAll()
        },
        changeType(){
          this.initAll()
        },
        changeTimeRange(){
          console.log(this.timeRange,123)
          this.initAll()
        },
        // 入参函数
        getParams1(){
          return {
            "g_bp_type":this.typeVal,
            "industry":this.industryVal,
            "score":this.scoreVal,
            "batch_number":this.timeRange,
            "username":getUsername()
          }
        },
        getParams2(){
          return {
            "g_bp_type":this.typeVal,
            "industry":this.industryVal,
            "score":this.scoreVal,
            "batch_number":this.timeRange,
            "bp_type_flag":this.tabBtn,//用户交互区别商业客户和渠道客户  0代表商业客户   1反之
            "page":this.currentPage,
            "pageSize":this.pageSize, //可不传，默认值为10
            "username":getUsername()
          }
        },
        // 客户流失分析卡片图
        async getBoxData(params){
          let res = await this.axios.post(`${this.testPort}/customerChurnAnalysis/lossCustormerAnalysis`,params)
          let resData = res.data.data
          this.resBoxData = resData
          this.boxData = this.language === 'en' ? this.resBoxData.en : this.resBoxData.zh
        },
        // 流失客户价值排名
        async getListData(params){
          this.loading.listPart = true
          let res = await this.axios.post(`${this.testPort}/customerChurnAnalysis/lossOfCustomerValue`,params)
          let resData = res.data.data
          setTimeout(()=>{
            this.loading.listPart = false
            this.totalPage = resData.total
            this.currentPage = resData.page
            this.listData = resData.data
            let listTop1 = {
              "batch_number":this.timeRange,
              "bp_type_flag":this.tabBtn,
              "boorder_cdbformalid":[this.listData[0].boorder_cdbformalid.toString()],
              "purchase_dur":this.listData[0].purchase_dur,
              "last_buy":this.listData[0].last_buy,
              "username":getUsername()
            }
            this.getDataEcharts1(listTop1)
            this.getDataEcharts2(listTop1)
          })
        },
        changeEcharts(params,flag){
          this.flag = flag
          let postData = {
            "batch_number":this.timeRange,
            "bp_type_flag":this.tabBtn,
            "boorder_cdbformalid":[params.boorder_cdbformalid.toString()],
            "purchase_dur":params.purchase_dur,
            "last_buy":params.last_buy,
            "username":getUsername()
          }
          this.getDataEcharts1(postData)
          this.getDataEcharts2(postData)
        },
        // 流失风险客户 echarts
        initEchartsDom(){
          this.echartDom.echartMix = this.echarts.init(document.getElementsByClassName('echartMix')[0], null, { renderer: 'canvas' })
          this.echartDom.echart1 = this.echarts.init(document.getElementsByClassName('echart1')[0], null, { renderer: 'canvas' })
          this.echartDom.echart2 = this.echarts.init(document.getElementsByClassName('echart2')[0], null, { renderer: 'canvas' })
        },
        async getDataEchartsMix(params){
          this.loading.echartMix = true
          let res = await this.axios.post(`${this.testPort}/customerChurnAnalysis/lossCustormerByDate`,params)
          let resData = res.data.data
          setTimeout(()=>{
            this.loading.echartMix = false
            this.drawBarMix(resData)
          },0)
        },
        drawBarMix(paramsData){
          if (paramsData.name.length !== 0) {
            let xAxisData = paramsData.name
            let data = paramsData.bar.value
            let legendData = []
            let barData = []
            for (let i in data) {
              legendData.push(data[i].name)
              barData.push({
                name: data[i].name,
                data: data[i].value,
                type: 'bar',
                barMaxWidth: 30,
                stack: 'sum'
              })
            }
            let option = {
              color: ['#7c8694','#f5a623', '#ffd34c', '#93b8e3'],
              tooltip: {
                confine: true,
                trigger: 'axis',
                axisPointer: {
                  type: 'shadow'
                },
                backgroundColor: 'rgba(255,255,255,1)',
                padding: [5, 10],
                textStyle: {
                  color: '#7588E4'
                },
                extraCssText: 'box-shadow: 0 3px 12px rgba(224,226,233,1)'
              },
              legend: {
                type: 'scroll',
                data: legendData,
                right: '2%'
              },
              grid: {
                left: '3%',
                right: '25%',
                bottom: '3%',
                containLabel: true
              },
              xAxis: [
                {
                  type: 'category',
                  axisTick: {
                    show: false
                  },
                  axisLabel:{
                    interval: 0,
                    color: '#666',
                    fontSize: 12
                  },
                  data: xAxisData
                }
              ],
              yAxis: [
                {
                  type: 'value',
                  name: '',
                  axisLabel: {
                    show: false
                  },
                  axisLine: {
                    show: false
                  },
                  splitLine: {
                    show: false
                  },
                  axisTick: {
                    show: false
                  }
                }
              ],
              series: barData
            }
            this.showNoData.echartMix = false
            this.echartDom.echartMix.clear()
            this.echartDom.echartMix.setOption(option)
          } else {
            this.echartDom.echartMix.clear()
            this.showNoData.echartMix = true
          }
        },
        // 交易周期 echarts
        async getDataEcharts1(params){
          this.loading.echart1 = true
          let res = await this.axios.post(`${this.testPort}/customerChurnAnalysis/tradingCycleByRecent`,params)
          let resData = res.data.data
          setTimeout(()=>{
            this.loading.echart1 = false
            this.drawBar(resData,'#3f9efe',0,'echart1',this.echartDom.echart1)
          },0)
        },
        async getDataEcharts2(params){
          this.loading.echart2 = true
          let res = await this.axios.post(`${this.testPort}/customerChurnAnalysis/tradingCycleByDate`,params)
          let resData = res.data.data
          setTimeout(()=>{
            this.loading.echart2 = false
            this.drawBar(resData,'#3f9efe',45,'echart2',this.echartDom.echart2)
          },0)
        },
        drawBar(paramsData,color,rotateDeg,noData,echartsObj){
          if (paramsData.name.length !== 0) {
            let xAxisData = paramsData.name
            let data = paramsData.bar.value
            let option = {
              color: color,
              xAxis: {
                type: 'category',
                axisTick: {
                  show: false
                },
                axisLabel: {
                  rotate: rotateDeg,
                  interval: 0,
                  color: '#666',
                  fontSize: 14
                },
                data: xAxisData
              },
              yAxis: {
                type: 'value',
                axisLabel: {
                  show: false
                },
                axisLine: {
                  show: false
                },
                splitLine: {
                  show: false
                },
                axisTick: {
                  show: false
                }
              },
              tooltip: {
                confine: true,
                trigger: 'axis',
                axisPointer: {
                  type: 'shadow'
                },
                backgroundColor: 'rgba(255,255,255,1)',
                padding: [5, 10],
                textStyle: {
                  color: '#7588E4'
                },
                extraCssText: 'box-shadow: 0 3px 12px rgba(224,226,233,1)'
              },
              series: [{
                data: data,
                type: 'bar',
                barMaxWidth: 30
              }]
            }
            this.showNoData[noData] = false
            echartsObj.clear()
            echartsObj.setOption(option)
          } else {
            echartsObj.clear()
            this.showNoData[noData] = true
          }
        },
        echartsResize(){
          setTimeout(() => {
            this.echartDom.echartMix.resize()
            this.echartDom.echart1.resize()
            this.echartDom.echart2.resize()
          },200)
        },
        changeTab(tabBtn) {
          console.log(tabBtn,'按钮名')
          this.getListData(this.getParams2())
        },
        handleSizeChange(val) {
          console.log(`每页 ${val} 条`)
          this.pageSize = val
          this.listData = []
          this.getListData(this.getParams2())
        },
        handleCurrentChange(val) {
          this.currentPage = val
          this.listData = []
          this.getListData(this.getParams2())
          this.listNum = val
        },
        initAll(){
          this.getBoxData(this.getParams1())
          this.getListData(this.getParams2())
          this.getDataEchartsMix(this.getParams1())
        }
      },
      computed: {
        ...mapGetters(['language','sidebar'])
      },
      watch: {
        'sidebar.opened': function () {
          this.echartsResize()
        },
        language() {
          if (this.language === 'en') {
            this.boxData = this.resBoxData.en
          } else if (this.language === 'zh') {
            this.boxData = this.resBoxData.zh
          }
        }
      },
      beforeMount(){
        this.getSelectData()
      },
      mounted(){
        this.initEchartsDom()
        this.initAll()
        window.onresize = () => {
          this.echartsResize()
        }
      }
    }
</script>

<style lang="scss" scoped>
  .CustomerLossWarning{
    padding: 20px 44px 0;
    .title{
      font-family:PingFangSC-Regular;
      font-size:18px;
      font-weight:bold;
      color:#000;
    }
    .select-module{
      .child-module{
        position: relative;
        .name{
          margin-right:10px;
        }
        .el-select, .el-input, .el-date-editor {
          /*width: calc(100% - 100px);*/
          width: calc(100% - 136px);
        }
      }
    }
    .box-part{
      display:flex;
      margin:20px 0;
      .box{
        flex:1;
        padding: 15px 28px 0 28px;
        .box-cont{
          margin-bottom: 20px;
          color:#fff;
          font-size:18px;
          .mediumFont{
            font-family:PingFangSC-Medium;
          }
          .regularFont{
            font-family:PingFangSC-Regular;
            float:right;
          }
        }
        .box-cont:nth-child(1){
          .regularFont{
            font-family:Helvetica;
            font-weight:bold;
            font-size:30px;
          }
        }
      }
      .box:nth-child(1){
        background-color: #7c8694;
      }
      .box:nth-child(2){
        background-color: #f5a523;
        margin:0 36px;
      }
      .box:nth-child(3){
        background-color: #409efe;
      }
    }
    .nodata{
      width: 100%;
      height: 100%;
      text-align:center;
      position: relative;
      top:100px;
      z-index:1;
    }
    .echartMix,.echart1,.echart2{
      width:100%;
      height:30vh;
    }
    .left-lists{
      margin:20px 0;
      .tabThree{
        position: relative;
        ul,li{
          list-style-type: none;
          margin:0;
          padding:0;
          overflow:hidden;
        }
        ul{
          position: absolute;
          right: 2vw;
        }
        li{
          float:left;
          width:88px;
          height:23px;
          line-height: 23px;
          border:1px solid #0090e9;
          text-align: center;
          cursor:pointer;
        }
        li.bgColor{
          background:#0090e9;
          color:#fff;
        }
      }
      .list-part{
        overflow: auto;
        height: 370px;
        margin-top: 30px;
        padding-left: 20px;
        li{
          cursor: pointer;
          margin-bottom:20px;
          list-style: none;
          span{
            font-family:PingFangSC-Regular;
            font-size:14px;
            color:#303133;
          }
        }
        li.activeColor,li:hover{
          span{
            color:#409eff;
          }
        }
      }
      .el-pagination{
        position: absolute;
        bottom: 3vh;
        right:20px;
      }
    }

  }
</style>
